﻿using System;
using System.Configuration;
using System.IO;
using System.Reflection;

namespace Infrastructure.Common.Data
{
    public class DbFactory
    {
        public static readonly DbFactory Instance = new DbFactory();

        private DbFactory()
        {
        }

        //简单工厂
        //public IDbHelper CreateDbHelper()
        //{
        //    //sqlType可以从appconfig里面取，
        //    var sqlType =ConfigurationManager.AppSettings["sqlType"];

        //    var connectionString = ConfigurationManager.ConnectionStrings[0];


        //    switch (sqlType)
        //    {
        //        case "sqlliet":
        //            return new SqliteHelper(connectionString.ConnectionString);
        //        case "sqlserver":
        //            return new SqlHelper(connectionString.ConnectionString);
        //        default:
        //            return new MySqlHelper();
        //    }
        //}

        /// <summary>
        ///     反射工厂
        /// </summary>
        /// <returns></returns>
        public IDbHelper CreateDbHelper()
        {
            string dllPath = ConfigurationManager.AppSettings["dllPath"]
                             ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Infrastructure.Common.dll");
            string dbhelpTypeName = ConfigurationManager.AppSettings["dbhelpTypeName"]
                                    ?? "Infrastructure.Common.Data.Imp.SqliteHelper";
            const string connectionString = "../../../../Database/TallyBook.db";

            //var dbhelpType = ConfigurationManager.AppSettings["dbhelpType"]
            //    ?? "Infrastructure.Common.Data.Imp.SqlHelper";
            //const string connectionString = "Data Source=localhost;Initial Catalog=db_Dress;Integrated security=SSPI";

            Assembly assembly = Assembly.LoadFile(dllPath);
            return
                assembly.CreateInstance(dbhelpTypeName, true, BindingFlags.CreateInstance, null,
                    new object[] {connectionString}, null, null) as IDbHelper;
        }
    }
}